package org.hibiscus.jdp.app.dbdoc.oracle;

import com.deepoove.poi.data.RowRenderData;
import org.hibiscus.jdp.app.dbdoc.DataSource;
import org.hibiscus.jdp.app.dbdoc.DbTypeConstants;
import org.hibiscus.jdp.app.dbdoc.POIFileUtils;
import org.hibiscus.jdp.app.dbdoc.TableStructureDoc;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Description: Oracle数据表结构文档
 *
 * @author 然诺
 * @date 2019/8/12
 */
public class OracleTableStructureDoc implements TableStructureDoc {

	@Override
	public String createDocument(DataSource dataSource, String outFilePath) {
		// 查询表信息
		String metaInfoSql = "select ut.table_name as table_name,ut.tablespace_name as engine,ut.buffer_pool as table_collation, " +
				"uc.table_type as table_type,uc.comments as table_comment,ut.last_analyzed as create_options " +
				"from user_tables ut,user_tab_comments uc where ut.table_name=uc.table_name";
		// 查询表结构信息
		String structureInfoSql = "select rownum as ordinal_position,c.nullable as is_nullable,c.data_default as column_default,c.data_type as data_type," +
				"c.data_length as character_maximum_length,t.column_name as column_name,t.column_type as column_type,t.comments as column_comment " +
				"from user_col_comments t,user_tab_columns c where c.column_name=t.column_name and c.table_name=t.table_name and t.table_name='";

		// 获取表元数据
		List<Map<String, String>> metaInfoList = OracleUtils.getTableStructureData(dataSource, metaInfoSql, true);

		List<Map<String, Object>> tableList = new ArrayList<>();
		int i = 0;
		for (Map<String, String> metaInfo : metaInfoList) {
			String sql = structureInfoSql + metaInfo.get("table_name") + "'";
			List<Map<String, String>> tableStructureData = OracleUtils.getTableStructureData(dataSource, sql, false);
			if (tableStructureData != null && !tableStructureData.isEmpty()) {
				List<RowRenderData> rowList = POIFileUtils.getRowRenderData(tableStructureData);
				tableList.add(POIFileUtils.mapData(metaInfo, rowList, ++i));
			}
		}

		// 默认生成的文件名
		String fileName = "数据库表结构(ORACLE)-" + System.currentTimeMillis() + ".docx";
		// 输出文件
		POIFileUtils.outFile(outFilePath + fileName, fileName, tableList, DbTypeConstants.ORACLE);
		return fileName;
	}

}
